<template>
  <div class="password-container">

    <!-- 密码修改区域 -->
    <el-card style="width: 50%;">
      <el-form ref="formRef" :model="user" :rules="rules" label-width="80px" style="padding-right: 20px">
        <el-form-item label="原始密码" prop="password">
          <el-input show-password v-model="user.password" @keyup.enter.native="update()"
                    placeholder="原始密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input show-password v-model="user.newPassword" @keyup.enter.native="update()"
                    placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input show-password v-model="user.confirmPassword" @keyup.enter.native="update()"
                    placeholder="确认密码"></el-input>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="update">确认修改</el-button>
        </div>
      </el-form>
    </el-card>

  </div>
</template>


<script>
export default {
  name: "Password",

  data() {
    // 自定义验证规则函数，用于确认密码与新密码是否一致
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码')) // 如果确认密码为空，提示错误
      } else if (value !== this.user.newPassword) {
        callback(new Error('确认密码错误')) // 如果确认密码与新密码不一致，提示错误
      } else {
        callback() // 验证通过
      }
    }

    return {
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'), // 从本地存储获取用户信息
      rules: { // 表单验证规则
        password: [
          {required: true, message: '请输入原始密码', trigger: 'blur'}, // 原始密码必填
        ],
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'}, // 新密码必填
        ],
        confirmPassword: [
          {validator: validatePassword, required: true, trigger: 'blur'}, // 确认密码使用自定义验证规则且必填
        ],
      }
    }
  },

  methods: {
    update() {
      this.$refs.formRef.validate((valid) => { // 验证表单数据
        if (valid) {
          this.user.password = this.user.newPassword // 将新密码赋值给原始密码
          // 发送更新用户信息的请求到服务器
          this.$request.put('/user/update', this.user).then(res => {
            if (res.code === '200') {
              // 如果更新成功
              this.$message.success('保存成功') // 显示成功消息
              this.$router.push('/login') // 跳转到登录页面
            } else {
              this.$message.error(res.msg) // 显示错误消息
            }
          })
        }
      })
    },
  }
}
</script>


<style scoped>
/deep/.el-form-item__label {
  font-weight: bold;
}

.password-container {
  height: 90vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background:
      linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)),
      url('@/assets/bg/password.png');
  background-position: center;
  background-size: 80% auto;
  background-repeat: no-repeat;
}
</style>